﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PMS.Utilities;
using PMS.ENT;
using PMS.BLL;

//OpenID
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using System.Web.Security;
using System.Net;
using System.IO;
using System.Text;


namespace PMS.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        
        public ActionResult Error()
        {
            return View();
        }

        #region Dashboard
        public ActionResult Dashboard()
        {
            try
            {
                #region Permission
                //if (Session["UserID"] == null || Utility.IntParse(Session["UserID"]) <= 0)
                //{
                //    return RedirectToAction("Login", "Home");
                //}
                //if (Utility.UserID <= 0 || Utility.RoleID <= 0 || string.IsNullOrWhiteSpace(Utility.Role))
                //{
                //    return RedirectToAction("Login", "Home");
                //}
                #endregion
                int page = MvcApplication.pageDefault;
                int pageSize = MvcApplication.pageSizeDefault;
                int totalRecords = 0;
                NotificationCollection listNotification = NotificationBLL.GetNotificationListByUserID(Utility.UserID, NotificationColumns.CreatedDate.ToString(), OrderDirection.DESC.ToString(), page, pageSize, out totalRecords);

                ViewData["OrderBy"] = NotificationColumns.CreatedDate.ToString();
                ViewData["OrderDirection"] = OrderDirection.DESC.ToString();
                ViewData["Page"] = page;
                ViewData["PageSize"] = pageSize;
                double PageNum = Math.Ceiling((double)totalRecords / pageSize);
                ViewData["PageNum"] = PageNum;
                ViewData["TotalRecord"] = totalRecords;
                return View(listNotification);
            }
            catch (DataAccessException)
            {
                TempData[PageInfo.Message.ToString()] = "BLM_ERR_Common";
                return RedirectToAction("Error", "Home");
            }
            catch (Exception ex)
            {
                LogBLL.LogEx("BLM_ERR_Common", ex);
                TempData[PageInfo.Message.ToString()] = "BLM_ERR_Common";
                return RedirectToAction("Error", "Home");
            }
        }

        [HttpPost]
        public ActionResult Dashboard(string action, int notificationID, string orderBy, string orderDirection, int page, int pageSize)
        {
            try
            {
                #region Permission
                //if (Session["UserID"] == null || Utility.IntParse(Session["UserID"]) <= 0)
                //{
                //    return RedirectToAction("Login", "Home");
                //}

                //if (Utility.UserID <= 0 || Utility.RoleID <= 0 || string.IsNullOrWhiteSpace(Utility.Role))
                //{
                //    return RedirectToAction("Login", "Home");
                //}

                #endregion

                #region DoAction
                if (action == "GotoPage" && notificationID > 0)
                {
                    NotificationENT notification = NotificationBLL.GetNotificationByID(notificationID);
                    if (NotificationBLL.UpdateNotificationIsRead(notificationID) > 0)
                    {
                        return Redirect(Utility.GetCurrentHost() + notification.Link);
                    }
                }
                #endregion

                #region LoadData
                int totalRecords = 0;

                NotificationCollection listNotification = NotificationBLL.GetNotificationListByUserID(Utility.UserID, orderBy, orderDirection, page, pageSize, out totalRecords);
                #endregion

                #region Pagination
                ViewData["OrderBy"] = orderBy;
                ViewData["OrderDirection"] = orderDirection;
                ViewData["Page"] = page;
                ViewData["PageSize"] = pageSize;
                double PageNum = Math.Ceiling((double)totalRecords / pageSize);
                ViewData["PageNum"] = PageNum;
                ViewData["TotalRecord"] = totalRecords;

                if (totalRecords > 0)
                {
                    if (page == PageNum)
                        ViewData["PageInfo"] = string.Format(" {0} - {1} / {2}.", (((page - 1) * pageSize) + 1).ToString(), totalRecords.ToString(), totalRecords.ToString());
                    else
                        ViewData["PageInfo"] = string.Format(" {0} - {1} / {2}.", (((page - 1) * pageSize) + 1).ToString(), (pageSize * page).ToString(), totalRecords.ToString());
                }
                #endregion

                return View(listNotification);
            }
            catch (DataAccessException ex)
            {
                TempData[PageInfo.Message.ToString()] = ex.Message;
                return RedirectToAction("Error", "Home"); ;
            }
            catch (Exception ex)
            {
                LogBLL.LogEx("BLM_ERR_Common", ex);
                TempData[PageInfo.Message.ToString()] = "BLM_ERR_Common";
                return RedirectToAction("Error", "Home");
            }
        }
        #endregion

        #region Login
        public ActionResult Login()
        {
            var openid = new OpenIdRelyingParty();
            IAuthenticationResponse response = openid.GetResponse();
            if (response != null && response.Status == AuthenticationStatus.Authenticated)
            {
                ViewData["Message"] = "Success! Identifier: " + response.ClaimedIdentifier;
                var fetch = response.GetExtension<FetchResponse>();
                if (fetch != null)
                {
                    string usercode = response.ClaimedIdentifier.ToString().Replace("https://www.google.com/accounts/o8/id?id=", "");
                    string email = fetch.GetAttributeValue("http://axschema.org/contact/email");
                    string fullname = fetch.GetAttributeValue("http://axschema.org/namePerson/first")
                                       + fetch.GetAttributeValue("http://axschema.org/namePerson/last");
                    
                    #region Do Action
                    int roleid = 0;

                    switch (email.Split('@')[1].ToLower())
                    {
                        case "sinhvien.hoasen.edu.vn":
                            roleid = 3;
                            break;
                        default:
                            TempData["Message"] = "Email is not valid in the system!";
                            return View();
                    }
                    UserENT user = UserBLL.GetUserByUserName(email.Split('@')[0] + "");

                    //Check user already create
                    if (user.UserID > 0)
                    {
                        Utility.UserID = user.UserID;
                        Utility.UserName = user.UserName;
                        Utility.Role = user.Role;
                        Utility.RoleID = user.RoleID;
                        //Session["UserID"] = user.UserID;

                        //Using cookies
                        SemesterENT semester = SemesterBLL.GetSemesterByDate(DateTime.Today);
                        Utility.semesterID = semester.SemesterID;

                        string strformcoookies = user.UserID + ";" + user.UserName + ";" + user.Role + ";" + user.RoleID + ";" + semester.SemesterID;
                        var authTicket = new FormsAuthenticationTicket(1, strformcoookies, DateTime.Now,
                                                      DateTime.Now.AddMinutes(30), true, "");
                        string cookieContents = FormsAuthentication.Encrypt(authTicket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                        {
                            Expires = authTicket.Expiration,
                            Path = FormsAuthentication.FormsCookiePath
                        };
                        Response.Cookies.Add(cookie);

                        return RedirectToAction("Dashboard");
                    }
                    else
                    {
                        //Insert new user
                        UserENT newuser = new UserENT();
                        newuser.CreatedDate = DateTime.Now;
                        newuser.DateOfBirth = DateTime.Now;
                        newuser.Email = email;
                        newuser.FullName = fullname;
                        newuser.Isdeleted = 0;
                        newuser.RoleID = roleid;
                        newuser.UserCode = usercode;
                        newuser.UserName = email.Split('@')[0] + "";
                        int result = UserBLL.InsertUser(newuser);
                        if (result > 0)
                        {
                            TempData["Message"] = "Success, First start up , please correct info in Account info's page";
                            Utility.UserID = result;
                            Utility.UserName = newuser.UserName;
                            Utility.Role = UserBLL.GetUserByID(result).Role;
                            Utility.RoleID = newuser.RoleID;
                            // Session["UserID"] = user.UserID;

                            SemesterENT semester = SemesterBLL.GetSemesterByDate(DateTime.Today);
                            Utility.semesterID = semester.SemesterID;

                            string strformcoookies = result + ";" + user.UserName + ";" + user.Role + ";" + user.RoleID + ";" + semester.SemesterID;
                            var authTicket = new FormsAuthenticationTicket(1, strformcoookies, DateTime.Now,
                                              DateTime.Now.AddMinutes(30), true, "");
                            string cookieContents = FormsAuthentication.Encrypt(authTicket);
                            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                            {
                                Expires = authTicket.Expiration,
                                Path = FormsAuthentication.FormsCookiePath
                            };
                            Response.Cookies.Add(cookie);


                            return RedirectToAction("AccountInfo", "Setting");
                        }
                        else if (result == -1)
                        {
                            TempData["Message"] = "Error Start up, Please try again later!";
                        }
                    }
                    #endregion
                }
            }
            else
            {
                ViewData["Message"] = "You are not logged in";
            }
            return View();
        }

        [HttpPost]
        public ActionResult Login(string action, string openid_identifier, string username, string password)
        {
            try
            {
                if (action == "loginPMS")
                {
                    UserENT user = UserBLL.GetUserByUserName(username);
                    if (user.UserID > 0)
                    {
                        if (user.Password == password)
                        {
                            Utility.UserID = user.UserID;
                            Utility.UserName = user.UserName;
                            Utility.Role = user.Role;
                            Utility.RoleID = user.RoleID;
                            // Session["UserID"] = user.UserID;
                            SemesterENT semester = SemesterBLL.GetSemesterByDate(DateTime.Today);
                            Utility.semesterID = semester.SemesterID;

                            //Using cookies

                            string strformcoookies = user.UserID + ";" + user.UserName + ";" + user.Role + ";" + user.RoleID + ";" + semester.SemesterID;
                            var authTicket = new FormsAuthenticationTicket(1, strformcoookies, DateTime.Now,
                                                          DateTime.Now.AddMinutes(30), true, "");
                            string cookieContents = FormsAuthentication.Encrypt(authTicket);
                            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                            {
                                Expires = authTicket.Expiration,
                                Path = FormsAuthentication.FormsCookiePath
                            };
                            Response.Cookies.Add(cookie);

                            if (Request.Params["ReturnURL"] != null)
                            {
                                return Redirect(Request.Params["ReturnURL"] + "");
                            }

                            return RedirectToAction("Dashboard");
                        }
                        else
                        {
                            ViewData["Message"] = "Invalid Password!";
                        }
                    }
                    else
                    {
                        ViewData["Message"] = "Invalid Username!";
                    }
                    return View();
                }
                else
                {
                    var openid = new OpenIdRelyingParty();
                    IAuthenticationRequest request = openid.CreateRequest(Identifier.Parse(openid_identifier));
                    var fetch = new FetchRequest();

                    //Add Attribute you need to retreive
                    fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);

                    //Mailbox Hoasen not include attribute below

                    //fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Company.CompanyName);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Company.JobTitle);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.City);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.PostalCode);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.State);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine1);
                    //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine2);
                    request.AddExtension(fetch);
                    return request.RedirectingResponse.AsActionResult();
                }
            }
            catch (DataAccessException ex)
            {
                TempData[PageInfo.Message.ToString()] = ex.Message;
                return RedirectToAction("Error", "Home"); ;
            }
            catch (Exception ex)
            {
                LogBLL.LogEx("BLM_ERR_Common", ex);
                TempData[PageInfo.Message.ToString()] = "BLM_ERR_Common";
                return RedirectToAction("Error", "Home");
            }
        }
        #endregion

        #region SignOut
        public ActionResult SignOut()
        {
            Session.RemoveAll();
            Session.Clear();
            Session.Abandon();
            string url = "https://accounts.google.com/Logout";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            FormsAuthentication.SignOut();
            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);
            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);
            FormsAuthentication.RedirectToLoginPage();
            return RedirectToAction("Login");
        }
        #endregion

        #region Notification
        public JsonResult GetNotification(int userID)
        {
            try
            {
                int value = 0;
                int ucurrent = Utility.UserID;
                value = NotificationBLL.GetNotificationUnreadNumber(userID);
                return Json(value, JsonRequestBehavior.DenyGet);

            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion
    }
}
